import axios, {AxiosInstance} from "axios";
import {ElMessage} from "element-plus";
import {Res} from "../types";


 const myAxios : AxiosInstance = axios.create({
    baseURL:  import.meta.env.VITE_BASE_URL,
    timeout: 8000,   //请求超时时间
})

// 全局设置 axios 发送请求带上cookie
myAxios.defaults.withCredentials = true

//请求拦截器
// myAxios.interceptors.request.use(config=>{
//
//     console.log(config)
//     return config;
// },error => {
//
//     showNotify({ type: 'danger', message: error });
//     return Promise.reject(error);
// })

// 添加响应拦截器
myAxios.interceptors.response.use( response =>  {
         return response.data;
    }, function (error) {
        ElMessage({
            message: error.message,
            type: 'error',
        })
        return Promise.reject(error);
});

async function getRequest<T>(url:string){
    let res : T  = await myAxios({
        url,
        method:`GET`
    });
    return res;
} 

async function postRequest <T>(url:string,data:any){
    let res : T  =  await myAxios({
        url,
        method:`POST`,
        data
    });
    return res;
}
async function putRequest <T>(url:string,data:any){
    let res : T  =  await myAxios({
        url,
        method:`PUT`,
        data
    });
    return res;
}
async function deleteRequest <T>(url:string){
    let res : T  =  await myAxios({
        url,
        method:`DELETE`
    });
    return res;
}

function ok<T>( data:T,msg:string="ok") : Res<T>{
    return {
        code: 200,
        data: data,
        flag: true,
        msg: msg
    }
}

function error<T>( data:T,msg:string="请求失败，请重试"): Res<T>{
    return {
        code: 500,
        data: data,
        flag: false,
        msg: msg
    }
}

export {myAxios,getRequest,postRequest,putRequest,deleteRequest,ok,error}